<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>论坛</title>
    <link rel="stylesheet" href="/css/common.css" type="text/css">
    <script src="/js/jquery/jquery-3.4.1.js"></script>
    <script src="/js/service/common.js"></script>
    <script>
        let time = 0;
        function init(userId, name) {
            time = 1;
            $("#common").html('');
            let param = userId ? `?userId=${userId}` : "";
            if(userId){
                param = `?userId=${userId}`;
                $("#title").text(`${name}的帖子`);
            }else{
                $("#title").text('全部帖子');
            }
            $.ajax({
                url: `/forum/forumList${param}`,
                dataType: "json",
                type: "GET",
                success: function (json) {
                    if(json.code === 200){
                        initHtml(json.data);
                    }else{
                        tipsMessage(json);
                    }
                }
            });
        }
        function initHtml(arr) {
            let html = "";
            let user = getUser();
            for(let i = 0, j = arr.length; i < j; i ++){
                let o = arr[i];
                html += getOneHtml(o, user.id);
            }
            $("#common").html(html);
        }
        function getOneHtml(obj, userId) {
            let admin = userId === 1;
            let commons = obj.commons;
            let commonHtml = '';
            let len, forumId = obj.id;
            if(commons && (len = commons.length) > 0){
                commonHtml = `<div style="padding: 2%;background: antiquewhite;">
                    <div style="margin: auto; width: 70%;">`;
                for(let i = 0; i < len; i ++){
                    let o = commons[i];
                    let prevUserId = o.prevUserId;
                    let prevHtml = "：";
                    if(prevUserId){
                        prevHtml = `回复<span class="forum-user-span href-next" onclick="init(${prevUserId}, ${o.prevUsername})">${o.prevUsername}：</span>`;
                    }
                    let deleteCommons = "";
                    if(admin || o.userId === userId){
                        deleteCommons = `<input class="delete-comment" value="删除评论" onclick="deleteComment(${o.id})">`;
                    }
                    commonHtml += `<span class="forum-user-span href-next" onclick="init(${o.userId}, '${o.username}')">${o.username}</span>${prevHtml}
                                    <span class="comment-content href-next" onclick="comment(this, 2, ${forumId}, ${o.id}, '${o.username}')">${o.content}</span>
                                    ${deleteCommons}<br>`;
                }
                commonHtml += `</div></div>`;
            }
            let deleteForum = "";
            if(admin || obj.userId === userId){
                deleteForum = `<input type="button" class="lang-btn" value="删除帖子" onclick="deleteForumById(${forumId})">`;
            }
            return `<div style="margin-top: 1%;">
                <div style="padding: 2%;">
                    <div style="position: relative">
                        <span>
                            <span style="padding-left: 10%;" class="forum-user-span href-next" onclick="init(${obj.userId}, '${obj.username}')">${obj.username}</span>
                            <span style="position: absolute; right: 10%;">${obj.createTime}</span><br>
                        </span>
                        <span class="forum-content">${obj.content}</span>
                    </div>
                </div>
                <div style="text-align: center">
                    <div hidden class="editData">
                        <textarea rows="3"></textarea>
                        <input type="button" class="btn" value="确定">
                    </div>
                    <div>
                        <input type="button" class="btn" value="评论" onclick="comment(this, 1, ${forumId})">
                        ${deleteForum}
                    </div>&nbsp;&nbsp;&nbsp;
                </div>
                ${commonHtml}
            </div><div style="height: 10px; background-color: white"></div>`;
        }
        init();
        function comment(o, flag, forumId, prevId, username) {
            $(".editData").each((i, e) => $(e).attr("hidden", "hidden"));
            let div = flag === 1 ? $(o).parent().prev("div") : $(o).parent().parent().prev("div").children()[0];
            $(div).removeAttr("hidden");
            $(div).next("div").attr("hidden", "hidden");
            let btn = $(div).children()[1];
            $(div).children()[0].placeholder = username ? `回复 ${username}` : "评论内容";
            $(btn).click(function () {
                submitComment(div, forumId, prevId);
            });
        }
        function deleteForumById(forumId) {
            if(confirm("确定删除这条记录吗？删除后下面的评论也会被删除，是否继续？")){
                $.ajax({
                    url: `/forum/deleteById/${forumId}`,
                    dataType: 'json',
                    type: 'DELETE',
                    success: function (json) {
                        if(json.code === 200){
                            alert("删除成功！！！");
                            init();
                        }else{
                            tipsMessage(json);
                        }
                    }
                });
            }
        }
        function deleteComment(commentId) {
            if(confirm("确定删除这条评论吗？删除后下面的评论也会被删除，是否继续？")){
                $.ajax({
                    url: `/comment/deleteById/${commentId}`,
                    dataType: 'json',
                    type: 'DELETE',
                    success: function (json) {
                        if(json.code === 200){
                            alert("删除成功！！！");
                            init();
                        }else{
                            tipsMessage(json);
                        }
                    }
                });
            }
        }
        function submitComment(div, forumId, prevId) {
            let val = $($(div).children()[0]).val();
            if(val && val.trim() !== ''){
                $.ajax({
                    url: '/comment/releaseComment',
                    dataType: 'json',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        forumId: forumId,
                        prevId: prevId,
                        content: val
                    }),
                    success: function (json) {
                        if(json.code === 200){
                            $(div).attr("hidden", "hidden");
                            $(div).next("div").removeAttr("hidden");
                            init();
                        }else{
                            tipsMessage(json);
                        }
                    }
                });
            }else{
                alert("不能发布空评论！！！");
                $(div).attr("hidden", "hidden");
                $(div).next("div").removeAttr("hidden");
            }
        }
        function releaseForum(btn) {
            let parent = $(btn).parent();
            parent.attr("hidden", "hidden");
            let div = parent.prev("div");
            div.removeAttr("hidden");
            let button = div.children()[1];
            let input = div.children()[0];
            $(input).removeAttr("hidden");
            $(input).val('');
            $(button).click(function () {
                if(time === 1){
                    time ++;
                    let val = $(input).val();
                    if(val && val.trim() !== ''){
                        $.ajax({
                            url: `/forum/releaseForum`,
                            dataType: 'json',
                            type: 'POST',
                            data: JSON.stringify({
                                content: val
                            }),
                            contentType: 'application/json',
                            success: function (json) {
                                if(json.code === 200){
                                    div.attr("hidden", "hidden");
                                    parent.removeAttr("hidden");
                                    init();
                                }else{
                                    tipsMessage(json);
                                }
                            }
                        });
                    }else{
                        alert("不能发布空帖子！！！");
                        div.attr("hidden", "hidden");
                        parent.removeAttr("hidden");
                    }
                }
            });
        }
    </script>
</head>
<body>
    <object class="object-top" data="/page/common/top"></object>
    <h3 style="text-align: center" id="title">全部帖子</h3>
    <div class="forum-div" id="common"></div>
    <div style="text-align: center" hidden>
        <textarea rows="3" placeholder="请输入发布内容"></textarea>
        <input type="button"class="btn" value="确定">
    </div>
    <div style="text-align: center">
        <input type="button" value="发帖" class="btn" onclick="releaseForum(this)">&nbsp;&nbsp;&nbsp;
        <input type="button" onclick="init()" value="全部帖子" class="lang-btn">
    </div>
</body>
</html>